package data

import (
	"commerce/common"
	"commerce/model"
	"fmt"
	"strings"
	"time"
)

func GetAdminByUp(username, pwd string) (*model.User, error) {

	sqlTpl := "select id, username FROM users where username = ? AND PASSWORD = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	var u model.User
	if err = stmt.QueryRow(username, pwd).Scan(&u.Id, &u.Username); err != nil {
		return nil, err
	}
	return &u, nil
}

func PageAdmin(pageNo, pageSize int, name string) (*common.Page, error) {

	whereSql := composeAdminSearchQuerySql(name)

	row := common.DB.QueryRow("select count(*) FROM users" + whereSql)
	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		return nil, err
	}
	stmt, err := common.DB.Prepare("select id, username, PASSWORD, email FROM users" + whereSql + " LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query((pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var us []model.User
	for rows.Next() {
		u := model.User{}
		if err := rows.Scan(&u.Id, &u.Username, &u.Password, &u.Email); err != nil {
			return nil, fmt.Errorf("管理员数据有误:%s", err.Error())
		}
		us = append(us, u)
	}
	return common.NewPage(us, pageNo, pageSize, totalRecords), nil
}

func GetAdminById(id int) (*model.User, error) {

	sqlTpl := "select id, username, PASSWORD, email FROM users where id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	var u model.User
	if err = stmt.QueryRow(id).Scan(&u.Id, &u.Username, &u.Password, &u.Email); err != nil {
		return nil, err
	}
	return &u, nil
}

func AddAdmin(u model.User) (int, error) {

	sqlTpl := "insert into users(username, PASSWORD, email, created_time) VALUES (?, ?, ?, ?)"
	result, err := common.DB.Exec(sqlTpl, u.Username, u.Password, u.Email, time.Now().Add(8*time.Hour))

	if err != nil {
		return 0, err
	}
	id, err := result.LastInsertId()

	if err != nil {
		return 0, fmt.Errorf("save admin insert id err: %v", err)
	}
	return int(id), nil
}

func UpdateAdmin(u model.User) (int, error) {

	sqlTpl := "update users set username = ?, PASSWORD = ?, email = ? WHERE id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()

	result, err := stmt.Exec(u.Username, u.Password, u.Email, u.Id)
	if err != nil {
		return 0, fmt.Errorf("update admin err:%v", err.Error())
	}
	rowsAffected, err := result.RowsAffected()
	return int(rowsAffected), err
}

func DeleteAdmin(id int) error {

	sqlTpl := "delete from users WHERE id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(id)
	if err != nil {
		return fmt.Errorf("delete admin:id:%d, err:%v", id, err.Error())
	}
	return err
}

func UpdateAdminPwdByEmail(email, npwd string) error {

	sqlTpl := "update users set PASSWORD = ? WHERE email = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(npwd, email)
	if err != nil {
		return fmt.Errorf("update admin pwd :email:%s, err:%v", email, err.Error())
	}
	return err
}

func composeAdminSearchQuerySql(name string) string {

	// 没有条件查询
	if len(name) == 0 {
		return ""
	}
	sb := strings.Builder{}
	sb.WriteString(" WHERE username like '%" + strings.TrimSpace(name) + "%'")

	return sb.String()
}
